
import pandas as pd
import os
import sys

CURRENT_PATH = os.getcwd()
sys.path.append(CURRENT_PATH)

from vals import name_list, city_grade, province_dict
from utils import get_all_name, get_key, columns_fill, columns_check
'''
生成部分默认特征

字段名称                      name                   func
========                    ========               ======
手机号城市			        did_city		       operator_loc
手机号省份			        did_province		   operator_loc
手机号运营商		            did_operator		   operator_loc
留资省份		                leads_province		   city2province
经销商省份			        dealer_province		   city2provinceF
经销商-手机号地区比较		    dealer_did_comp		   dealer_did
留资-手机号地区比较		    leads_did_comp		   leads_did
留资-经销商地区比较		    leads_dealer_comp	   leads_dealer
留资-城市等级		            leads_city_grade	   city_grade_info
经销商-城市等级		        dealer_city_grade	   city_grade_info
手机号-城市等级		        did_city_grade		   city_grade_info
留资大区		                leads_regional		   province2regional
经销商大区		            dealer_regional		   province2regional
手机号大区		            did_regional		   province2regional
姓名-词性		            name1		           name_wash
姓名是否规整		            name2		           name_wash
'''


__all__ = ['etl_funcs', 'city2province' , 'province2regional', 'city_grade_info' ,\
           'operator_loc' , 'dealer_did' , 'leads_dealer' , 'leads_did' , 'name_wash']



def etl_funcs(df: pd.DataFrame, DLC_list: list):
    '''
    用于查看需要手动增加的函数

    :param df:
    :param funcs:
    :return:
    '''
    df2 = df.copy()
    lack_token_list = []
    for DLC_val in DLC_list:
        if DLC_val not in df2.columns.tolist():
            lack_token_list.append(DLC_val)
    return lack_token_list



def city2province(df: pd.DataFrame, columns=None):
    '''
    根据城市信息匹配省份
    可输入columns生成指定的字段，默认生成 ['leads_province', 'dealer_province', 'did_province']

    :param df:
    :param columns: 可为 None, 可输入city字段生成province字段
    :return:
    '''
    if not columns:
        columns = ['leads', 'dealer', 'did']
    for col in columns:
        try:
            df[col + '_province'] = df[col + '_city'].apply(lambda x: get_key(province_dict, x))
        except Exception as e:
            print(e)
    return df

def province2regional(df):
    '''
    根据省份匹配大区
    可输入columns生成指定的字段，默认生成['leads_regional', 'dealer_regional' , 'did_regional']

    :param df:
    :return:
    '''

    regional = pd.read_excel("./ldos_leads_rating/ldos_features/regional.xlsx")
    regional = regional.drop(columns=['省份简称'])
    columns = ['leads', 'dealer', 'did']
    for col in columns:
        try:
            regional.columns = [col + '_regional', col + '_province']
            df = df.merge(regional, how='left', on=col + '_province')
        except Exception as e:
            pass
    return df


def city_grade_info(df: pd.DataFrame):
    '''
    城市等级信息
    可输入columns生成指定的字段，默认生成['dealer_city_grade', 'did_city_grade', 'leads_city_grade']

    :param df:
    :return:
    '''
    columns = columns_check(['dealer_city', 'did_city', 'leads_city'], df.columns)
    for col in columns:
        try:
            df[col + '_grade'] = df[col].apply(lambda x: get_key(city_grade, x))
        except Exception as e:
            pass
    return df

def operator_loc(df: pd.DataFrame):
    '''
    获取运营商数据字段 'did_operator', 'did_province', 'did_city'

    :param df:
    :return:
    '''
    if 'mobile_info' not in globals():
        global mobile_info

        mobile_info = pd.read_csv("./ldos_leads_rating/ldos_features/mobiles.csv", engine='python', encoding='GBK')

        mobile_info.columns = ['phone_7', 'did_operator', 'did_province', 'did_city']
        mobile_info['phone_7'] = mobile_info['phone_7'].astype(str)

    df['phone_7'] = df['mobile'].astype(str).str.slice(stop=7)
    for col in ['did_operator', 'did_province', 'did_city']:
        if col in df.columns:
            df = df.drop(columns=col)
    df = df.merge(mobile_info, how='left', on='phone_7')
    df = columns_fill(df, ['did_operator', 'did_province', 'did_city'])
    return df



def dealer_did(dealer_city, did_city, dealer_province, did_province):
    if (dealer_city == 'dealer_city') and (did_city == 'did_city'):
        return 'ddid_both_null'
    elif (dealer_city == 'dealer_city') and (did_city != 'did_city'):
        return 'ddid_dealer_null'
    elif (dealer_city != 'dealer_city') and (did_city == 'did_city'):
        return 'ddid_did_null'
    elif dealer_city == did_city:
        return 'ddid_city_equal'
    elif (dealer_city != did_city) and (dealer_province == did_province):
        return 'ddid_prov_equal'
    elif (dealer_city != did_city) and (dealer_province != did_province):
        return 'ddid_none_equal'


def leads_dealer(leads_city, dealer_city, leads_province, dealer_province):
    if (leads_city == 'leads_city') and (dealer_city == 'dealer_city'):
        return 'dleads_both_null'
    elif (leads_city == 'leads_city') and (dealer_city != 'dealer_city'):
        return 'dleads_leads_null'
    elif (leads_city != 'leads_city') and (dealer_city == 'dealer_city'):
        return 'dleads_dealer_null'
    elif leads_city == dealer_city:
        return 'dleads_city_equal'
    elif (leads_city != dealer_city) and (leads_province == dealer_province):
        return 'dleads_prov_equal'
    elif (leads_city != dealer_city) and (leads_province != dealer_province):
        return 'dleads_none_equal'


def leads_did(leads_city, did_city, leads_province, did_province):
    if (leads_city == 'leads_city') and (did_city == 'did_city'):
        return 'ldid_both_null'
    elif (leads_city == 'leads_city') and (did_city != 'did_city'):
        return 'ldid_leads_null'
    elif (leads_city != 'leads_city') and (did_city == 'did_city'):
        return 'ldid_did_null'
    elif leads_city == did_city:
        return 'ldid_city_equal'
    elif (leads_city != did_city) and (leads_province == did_province):
        return 'ldid_prov_equal'
    elif (leads_city != did_city) and (leads_province != did_province):
        return 'ldid_none_equal'




def name_wash(df):

    '''
    生成衍生字段 name1, name2

    :param df:
    :return:
    '''

    df['name'] = df['name'].astype(str)
    df['name1'] = df['name'].map(lambda x: get_all_name(x))
    df['name2'] = df.apply(lambda x: 1 if ('nr' in x['name1']) or ('先生' in x['name']) or ('小姐' in x['name']) or (
            x['name'] in name_list) else 0,
                           axis=1)
    return df










